import React from "react";
import { usePathname } from "next/navigation";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import { findAllMenuItemByPath } from "../../config/menu";
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";
import Forbidden from "@/app/forbidden";

/**
 * 统一权限校验拦截器
 * @param children
 * @constructor
 */
const AccessLayout: React.FC<{
  children: React.ReactNode; // 子元素类型定义
}> = ({ children }) => {
  // 获取当前的页面路径
  const pathName = usePathname();
  // 获取当前登录的用户
  const loginUser = useSelector((state: RootState) => state.loginUser);
  // 判断当前路径需要的权限
  const menu = findAllMenuItemByPath(pathName);
  console.log("当前访问的页面路径为：", menu);
  const needAccess = menu?.access ?? ACCESS_ENUM.NOT_LOGIN;
  // 校验权限
  const canAccess = checkAccess(loginUser, needAccess);
  if (!canAccess) {
    return <Forbidden />;
  }
  return <>{children}</>;
};

export default AccessLayout;
